#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>


void worker(int cnt)
{
   printf("I am a child, pid: %d, cnt: %d\n", getpid(),  cnt);
}

int main()//子进程运行同时，父进程同时做检测
{
  pid_t id = fork();
  if(id == 0)
  {
    //child
    int cnt = 5;
    while(cnt)
    {
      worker(cnt);
      sleep(2);
      cnt--;

    }

   exit(0);
  }
  while(1)//父进程的等待
  {

      //father
      int status = 0;
      pid_t rid = waitpid(id, &status, WNOHANG);
      if(rid > 0)
      {
        // wait success, child quit now;
        printf("child quit success, exit code: %d, exit signal: %d\n", (status>>8)&0xFF, status&0x7F);
        break;
      }
      else if(rid == 0)//若没有while循环，父进程在此处分流后会直接退出，子进程继续执行变为孤儿进程
      {
        // wait success, but child not quit
        printf("child is alive,wait again,father do other thing.....\n");
      }
      else{
        //wait failed, child unknow
        printf("wait failed!\n");
        break;
      }
      sleep(1);
  }

  


  return 0;
}
